import network
import time
from machine import Timer
import settings as st

class WiFi():
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self._tim = Timer(0)
        self.timer_count = 0
        self.timeout = 5
        self.isconnected = self.wlan.isconnected
        self.busy = False
        
    def connect(self):
        if not self.busy:
            self._tim.init(period=1, mode=Timer.ONE_SHOT, callback=self.connect_handler)
    
    def connect_handler(self, ev):
        self.busy = True
        # print('connecting to network...')
        self.wlan.active(True)
        # print("wifi connect handler")
        for config in st.WIFI_CONFIG:
            if self.isconnected():
                break
            essid = config["ssid"]
            password = config["psk"]
            print("try %s"%essid)
            self.wlan.connect(essid, password)
            for _ in range(self.timeout):
                if self.wlan.isconnected():
                    break
                time.sleep(1)
            else:
                continue
            break
        else:
            self.wlan.active(False)
            self.busy = False
            self.on_timeout()
            return False
        # print('network config:', self.wlan.ifconfig())
        self.ifconfig = self.wlan.ifconfig()
        self.ip = self.ifconfig[0]
        self.mask = self.ifconfig[1]
        self.gateway = self.ifconfig[2]
        self.busy = False
        self.on_connected()
        return True

    def on_connected(self):
        pass

    def on_timeout(self):
        pass

    def search(self):
        li = []
        ip = self.ip.split(".")
        #print(ip)
        mask = self.mask.split(".")
        for i in range(2, 255):
            ip[3] = str(i)
            if mask[2] == 0:
                for j in range(2, 255):
                    ip[2] = str(j)
                    li.append(".".join(ip))
            else:
                #print(ip)
                li.append(".".join(ip))
        self.avaiable_list = []
        for ip in li:
            print("test: %s" % ip)
            name = self.check_available(url)
            if name:
                avaiable_list.append(name)
        return avaiable_list

    def check_available(self, ip):
        try:
            uri = "ws://" + ip + ":5000"
            ws = WS.connect(uri)
            self.avaiable_list.append(ip)
            return True
        except OSError:
            return False

    def close(self):
        self.wlan.active(False)